package org.groupg.mockdatabyspring.morkdata.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
import org.apache.tinkerpop.gremlin.structure.Graph;
import org.apache.tinkerpop.gremlin.structure.T;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerGraph;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

import static org.apache.tinkerpop.gremlin.process.traversal.AnonymousTraversalSource.traversal;

/**
 * 图数据库使用工具类
 */
@Slf4j
@Component
public class GraphUtils {

    /**
     * 默认的构造方法
     */
    @Autowired
    public GraphUtils() {
        /**
         * 依赖的配置数据
         */
//        HGConfiguration config = new HGConfiguration();
//        config.setTransactional(false);
//        config.setSkipOpenedEvent(true);
//        this.graph = HGEnvironment.get(mockDataConfig.getHyperGraphDBPath());
    }


//    private Graph graph;

    /**
     * 图数据库组件 用完之后需要调用.close方法关闭
     * @return 返回图数据库组件
     */
    public Graph getNewGraph() {
        Graph graph = TinkerGraph.open();
        GraphTraversalSource g = traversal().withEmbedded(graph);
        return graph;
    }

    /**
     * 示例
     *
     * @param args 命令行实例参数
     * @throws Exception 空异常处理
     */
    public static void main(String[] args) throws Exception {
        // 创建 TinkerGraph 实例
        Graph graph = TinkerGraph.open();
        GraphTraversalSource g = traversal().withEmbedded(graph);
        List<Vertex> vertices = g.V().toList();

        try {
            // 添加节点和边
            Vertex v1 = graph.addVertex(T.label, "Person", "name", "Alice");
            Vertex v2 = graph.addVertex(T.label, "Person", "name", "Bob");
            v1.addEdge("knows", v2);

            // 执行查询
            graph.traversal()
                    .V() // 选择所有顶点
                    .hasLabel("Person") // 过滤出标签为 "Person" 的顶点
                    .range(0, 10) // 限制结果数量为 10（这里其实没有必要，因为通常不会有那么多）
                    .forEachRemaining(vertex -> {
                        System.out.println("Vertex ID: " + vertex.id());
                        System.out.println("Vertex Name: " + vertex.properties("name"));
                        System.out.println("Vertex Label: " + vertex.label());
//                        System.out.println("Vertex 'knows' Edges: " + vertex);
                        System.out.println();
                    });

        } finally {
            // 关闭图形数据库
            graph.close();
        }
    }
}
